package com.fd.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fd.dao.ILoginDao;
import com.fd.dao.imp.LoginDao;
import com.fd.pojo.UserInfo;
import com.fd.utils.SSoUtils;
import com.lizeng.utils.MyDigestUtils;

/***
 * SSO登录
 * 
 * @author 符冬
 * 
 */
public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = -2658986906238704629L;
	private ILoginDao logindao = new LoginDao();

	/***
	 * 接受客户端登录验证请求
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String loginId = SSoUtils.getCookieValue(request, "loginId");
		String loginCode = SSoUtils.getCookieValue(request, "loginCode");
		String url = request.getParameter("url");
		if (url != null && loginCode != null && loginId != null
				&& loginCode.equals(MyDigestUtils.shaDigest(loginId, "fudong"))) {

			redirect(request, response);
		} else {

			request.setAttribute("url", url);
			request.getRequestDispatcher("/WEB-INF/page/login.jsp").forward(
					request, response);
		}
	}

	/**
	 * 登录
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String userName = request.getParameter("userName");
		String pwd = request.getParameter("password");
		if (userName != null && pwd != null) {
			UserInfo user = logindao.getUserInfo(userName, pwd);
		}

		SSoUtils.addCookie(response, "loginId", "112233", "ranch.com");
		SSoUtils.addCookie(response, "loginCode",
				MyDigestUtils.shaDigest("112233", "fudong"), "ranch.com");

		redirect(request, response);

	}

	private void redirect(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String url = request.getParameter("url");
		StringBuilder bd = new StringBuilder(url);
		if (url.indexOf("?") != -1) {
			bd.append("&loginId").append("=").append("112233");
			bd.append("&loginCode").append("=")
					.append(MyDigestUtils.shaDigest("112233", "fudong"));

		} else {
			bd.append("?loginId").append("=").append("112233");
			bd.append("&loginCode").append("=")
					.append(MyDigestUtils.shaDigest("112233", "fudong"));
		}
		response.sendRedirect(bd.toString());
	}
}
